const {jwtAdminRouter} = require('../../util')
const {query} = require('../../db')
let router = jwtAdminRouter()

router.get('/', async (req, res, next)=>{
    let page = req.query.page || 1
    let pageSize = req.query.page_size || 20

    let offset = (page-1)*pageSize
    let sql = `SELECT * FROM categories ORDER BY id DESC LIMIT ${offset},${pageSize}`

    let data = await query(sql).catch(next)
    if(data === undefined) return

    let total = await query('SELECT COUNT(*) total FROM categories').catch(next)
    if(total === undefined) return

    res.json({
        'ok': 1,
        'total': total[0].total,
        data
    })
})

router.post('/', async (req, res, next)=>{
    let cat_name = req.body.cat_name

    let sql = 'INSERT INTO categories SET ?'
    let ret = await query(sql, {cat_name}).catch(next)
    if(ret === undefined) return 

    res.json({
        'ok': 1
    })
})

router.put('/:id', async (req, res, next)=>{
    let cat_name = req.body.cat_name
    let id = req.params.id

    let sql = 'UPDATE categories SET ? WHERE id = ?'
    let ret = await query(sql, [{cat_name}, id]).catch(next)
    if(ret === undefined) return 

    res.json({
        'ok': 1
    })
})

router.delete('/:id', async (req, res, next)=>{
    let id = req.params.id

    let sql = 'DELETE FROM categories WHERE id = ?'
    let ret = await query(sql, id).catch(next)
    if(ret === undefined) return 

    res.json({
        'ok': 1
    })
})

router.get('/:id', async (req, res, next)=>{
    let id = req.params.id

    let sql = 'SELECT * FROM categories WHERE id = ?'
    let ret = await query(sql, id).catch(next)
    if(ret === undefined) return 

    res.json({
        'ok': 1,
        'data': ret[0]
    })
})

module.exports = router